package tt.dz.common;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 公用方法
 * @author 谢龙飞
 *
 */
public final class PublicFunc {
	
	
	/**字符数组*/
	public static final String[] charArray={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
		"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
		"0","1","2","3","4","5","6","7","8","9"};
	
	/**定义字符数组长度*/
	public static Integer charArrayLength=0;
	
	/**HTTP客户端*/
	public static final HttpClient client = new HttpClient();;
	
	/**
	 * 静态代码块
	 */
	static{
		//设置字符数组长度（首次有效）
		charArrayLength = charArray.length-1;
	}
	
	/**
	 * 得到6个随机字符组成的字符串
	 * @return 组成的字符串
	 */
	public static final String getRandString(){
		
		String resultStr = "";
		for (int i = 0; i < 6; i++) {
			int arrayIndex = new Random().nextInt(charArrayLength);
			resultStr += charArray[arrayIndex];
		}
		return resultStr;
	}
	
	/**
	 * json拼接
	 * @param code	编码
	 * @param msg	消息
	 * @param data	数据
	 * @return
	 */
	public static final String getOutStr(String code,String msg,Object data){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("code", code);
		map.put("msg", msg);
		map.put("data", data);
		//转换JSON并返回
		return JSON.toJSONString(map,SerializerFeature.WriteMapNullValue);
	}
	/**
	 * json转换
	 * @param obj Object对象
	 * @return 转换过的json字符串
	 */
	public static final String getJsonStr(Object obj){
		return JSONObject.toJSONString(obj);
	}
	
	/**
	 * json转换
	 * @param obj Object对象
	 * @return 转换过的json字符串
	 */
	public static final String MD5(String str){
		try {
			return DigestUtils.md5Hex(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 用户卡校验位
	 * @param preCard	用户卡号（不包含最后校验位）
	 * @return 最终卡号
	 */
	public static final Integer checkOutUserCardByte(String preCard){
		
		Integer preCardLength = preCard.length();
		Integer checkSum = 0;
		for (int i = 0; i < preCardLength; i++) {
			Integer charNum = Integer.parseInt(preCard.charAt(i)+"");
			//如果为偶数位（不是偶数）
			if(i%2==1){			
				//直接相加
				checkSum+=charNum;
			}
			//奇数位
			else{
				//乘以2
				charNum*=2;
				//如果相乘>=10
				if(charNum>=10){
					String charNumStr = String.valueOf(charNum.intValue());
					//取个位数相加
					checkSum += Integer.parseInt(charNumStr.substring(charNumStr.length()-1));
					//取十位数相加
					checkSum += Integer.parseInt(charNumStr.substring(charNumStr.length()-2,charNumStr.length()-1));
				}
				else{
					//如果小于10直接相加
					checkSum+=charNum;
				}
			}
		}
		//如果相加值大于10
		if(checkSum>10){
			String checkSumStr = String.valueOf(checkSum+"");
			//取到最后一位字符（个位）转化为数字并用10相减得到校验码
			checkSum = Integer.parseInt(checkSumStr.substring(checkSumStr.length()-1));
			checkSum = 10-checkSum;
			//如果最后结果为10就返回0
			if(checkSum==10){
				return 0;
			}
			//其他则直接返回
			return checkSum;
		}
		//如果为否
		else{
			//直接用10相减得到校验码
			return 10-checkSum;
		}
	}
	/**
	 * post请求
	 * @param urlValue 请求地址
	 * @param map 参数表
	 * @return
	 */
	public static final String postRequestByUrl(String urlValue, Map<?, ?> map) {

		PostMethod method = new PostMethod(urlValue);
		//设置请求头
		method.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
		try {
			//设置请求参数
			for (Iterator<?> iter = map.keySet().iterator(); iter.hasNext();) {
				//得到参数名
				String key = iter.next() + "";
				//得到参数值
				String value = map.get(key) + "";
				method.addParameter(key, value + "");
			}
			//执行
			client.executeMethod(method);
			//返回 appserver的返回数据
			return method.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
			return Constants.JsonResponseCode.HTTPREQUEST_ERROR;
		} finally {
			//断开连接（必须）
			method.releaseConnection();
		}
	}

	/**
	 * get请求
	 * @param urlValue 请求地址
	 * @return
	 */
	public static final String getRequestByUrl(String urlValue) {

		System.out.println(urlValue);
		GetMethod method = new GetMethod(urlValue);
		//设置请求头
		method.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
		try {
			//执行
			client.executeMethod(method);
			//返回 appserver的返回数据
			return method.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
			return Constants.JsonResponseCode.HTTPREQUEST_ERROR;
		} finally {
			//断开连接（必须）
			method.releaseConnection();
		}
	}
	public static void main(String[] args) {
		System.out.println(checkOutUserCardByte("1880800280000000002"));
	}
}
